package org.uni_hi.lsep.gui.util;

import java.awt.Dimension;

import javax.swing.JComboBox;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;

public class ComboPopupMenuListener extends Object implements PopupMenuListener {

	@Override
	public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
		JComboBox box = (JComboBox) e.getSource();
		Object comp = box.getUI().getAccessibleChild(box, 0);
		if (!(comp instanceof JPopupMenu)) return;
		JScrollPane scrollPane = (JScrollPane) ((JPopupMenu) comp).getComponent(0);
		BasicComboPopup pop=(BasicComboPopup) comp;
		Dimension size=new Dimension(400,400);
		pop.setMaximumSize(size);
		scrollPane.setMaximumSize(size);

		scrollPane.validate();
		scrollPane.getViewport().validate();
		size=(Dimension) scrollPane.getPreferredSize().clone();
		size.height+=2;
		size.width=scrollPane.getViewport().getPreferredSize().width;
		if(size.width<box.getSize().width){
			size.width=box.getSize().width;
		}else{
			size.width+=scrollPane.getVerticalScrollBar().getPreferredSize().width+5;
		}
		pop.setPreferredSize((Dimension) size.clone());
	}

	@Override
	public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}

	@Override
	public void popupMenuCanceled(PopupMenuEvent e) {}
}

